/*
 * Copyright 2006-2015 Transsion.com All right reserved. This software is the confidential and proprietary information
 * of Transsion.com ("Confidential Information"). You shall not disclose such Confidential Information and shall use it
 * only in accordance with the terms of the license agreement you entered into with Transsion.com.
 */
package com.yunji.framework_template.common.util;

import java.io.File;
import java.io.IOException;
import java.net.InetAddress;

import javax.annotation.PostConstruct;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.maxmind.geoip2.DatabaseReader;
import com.maxmind.geoip2.model.CountryResponse;

/**
 * ClassName:GeoUtils <br/>
 * Date: 2016年12月9日 上午10:13:41 <br/>
 * 
 * @author fenglibin
 * @version
 * @see
 */
@Component
public class GeoUtils {

    private static final Logger   logger = Logger.getLogger(GeoUtils.class);
    private static DatabaseReader reader;
    @Value("#{settings['geoDataPath']}")
    private String                geoDataPath;

    @PostConstruct
    private void init() {
        try {
            logger.info("The path of GeoIP.dat is:" + geoDataPath);
            File geoFile = new File(geoDataPath);
            if (!geoFile.exists()) {
                logger.warn("The path " + geoDataPath + " of GeoIP.dat is not exists.");
                return;
            }
            reader = new DatabaseReader.Builder(new File(geoDataPath)).build();
            logger.info("init LookupService successfully");
        } catch (IOException e) {
            logger.error("Init LookupService error: " + e.getMessage(), e);
        }
    }

    /**
     * 根据IP地址获取国家代码
     * 
     * @param ip
     * @return
     */
    public static String getCountryCodeByIP(String ip) {
        if (reader == null) {
            return null;
        }
        try {
            InetAddress ipAddress = InetAddress.getByName(ip);
            // Replace "city" with the appropriate method for your database, e.g.,
            // "country".
            CountryResponse response = reader.country(ipAddress);
            return response.getCountry().getIsoCode();
        } catch (Exception e) {
            //logger.error("getCountryCode error happened:" + e.getMessage(), e);
            return "--";
        }
    }

}
